'use client';

import React, { useState, useEffect } from 'react';
import { useSocket } from '@/hooks/use-socket';
import { Avatar, AvatarFallback, AvatarImage } from '@/components/ui/avatar';
import { Badge } from '@/components/ui/badge';
import { Edit } from 'lucide-react';
import { BlockEditData } from '@/types/socket';

interface BlockEditorIndicatorProps {
  projectId: string;
  documentId: string;
  blockId: string;
  className?: string;
  onActiveEditorsChange?: (count: number) => void;
}

export function BlockEditorIndicator({ 
  projectId, 
  documentId, 
  blockId,
  className = '',
  onActiveEditorsChange
}: BlockEditorIndicatorProps) {
  const [editors, setEditors] = useState<{ userId: string; userName: string; userColor?: string; userImage?: string }[]>([]);
  const { socket, isConnected } = useSocket();
  
  useEffect(() => {
    if (!socket || !isConnected) return;
    
    // 监听块编辑状态变化
    const handleBlockEdit = (data: BlockEditData) => {
      if (data.projectId !== projectId || data.docId !== documentId || data.blockId !== blockId) return;
      
      if (data.isEditing) {
        // 添加编辑者
        setEditors(prev => {
          const newEditors = [...prev];
          const existingEditorIndex = newEditors.findIndex(e => e.userId === data.userId);
          
          if (existingEditorIndex === -1) {
            newEditors.push({
              userId: data.userId,
              userName: data.userName,
              userColor: data.userColor,
              userImage: undefined
            });
          }
          
          // 通知编辑者数量变化
          if (onActiveEditorsChange) {
            onActiveEditorsChange(newEditors.length);
          }
          
          return newEditors;
        });
      } else {
        // 移除编辑者
        setEditors(prev => {
          const newEditors = prev.filter(e => e.userId !== data.userId);
          
          // 通知编辑者数量变化
          if (onActiveEditorsChange) {
            onActiveEditorsChange(newEditors.length);
          }
          
          return newEditors;
        });
      }
    };
    
    // 使用socket.on直接监听事件
    socket.on('block-editing', handleBlockEdit);
    
    return () => {
      // 移除事件监听
      socket.off('block-editing', handleBlockEdit);
    };
  }, [socket, isConnected, projectId, documentId, blockId, onActiveEditorsChange]);
  
  // 如果没有编辑者，不显示任何内容
  if (editors.length === 0) return null;
  
  // 获取用户初始字母（用于头像）
  const getUserInitials = (name: string) => {
    return name
      .split(' ')
      .map(part => part[0])
      .join('')
      .toUpperCase()
      .substring(0, 2);
  };
  
  return (
    <div className={`flex items-center ${className}`}>
      {editors.length === 1 ? (
        // 单个编辑者显示详细信息
        <div className="flex items-center gap-1">
          <Avatar className="h-6 w-6" style={{ borderColor: editors[0].userColor, borderWidth: '2px' }}>
            {editors[0].userImage ? (
              <AvatarImage src={editors[0].userImage} alt={editors[0].userName} />
            ) : (
              <AvatarFallback>{getUserInitials(editors[0].userName)}</AvatarFallback>
            )}
          </Avatar>
          <span className="text-xs">{editors[0].userName} 正在编辑</span>
        </div>
      ) : (
        // 多个编辑者显示数量
        <Badge variant="outline" className="bg-amber-100 text-amber-800 border-amber-200 flex items-center gap-1">
          <Edit className="h-3 w-3" />
          <span>{editors.length} 人正在编辑</span>
        </Badge>
      )}
    </div>
  );
} 